//
//  XMAlbumSubController.m
//  XiaoMiao
//
//  Created by 23 on 2018/1/28.
//  Copyright © 2018年 smallyou. All rights reserved.
//


//controller
#import "XMAlbumSubController.h"
#import "SuccessToOriginController.h"
#import "ProjectSeletedController.h"
#import "XMPhotoScanController.h"
#import "XMSinglePicScanController.h"
#import "XMCompareScanController.h"
#import "XMCameraTimeAndAngleViewController.h"

//view
#import "XMAlbumSubCell.h"
#import "XMAlbumSubHeadView.h"
#import "XMAlbumSubNewView.h"
#import "XMShowRemarkView.h"
#import "XMTitleAlterView.h"

//model
#import "XMAlbumSubModel.h"
#import "XMAlbumSubsubModel.h"

@interface XMAlbumSubController () <UITableViewDelegate, UITableViewDataSource, XMAlbumSubCellDelegate, KLTableViewPlaceHolderProtocol>
/**items*/
@property(nonatomic,strong) NSMutableArray <XMAlbumSubModel *>*items;
/** <#属性#> */
@property (nonatomic, strong) UITableView *tableView;
/** <#属性#> */
@property (nonatomic, strong) UIButton *confirmUploadButton;
/** <#Description#> */
@property (nonatomic, strong) XMAlbumSubNewView *albumSubNewView;
@end

@implementation XMAlbumSubController

static NSString * const Id = @"Album";

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupUI];
    
    [self loadAlbumDataRequest];
}

#pragma mark - UI
- (void)setupUI
{
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(0);
    }];
    
    if (self.isUpdataOperate) {
        [self.view addSubview:self.confirmUploadButton];
        [self.confirmUploadButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.bottom.mas_equalTo(@0);
            make.height.mas_equalTo(@50);
        }];
        
        [self.tableView setContentInset:UIEdgeInsetsMake(0, 0, 50, 0)];
        
    }else {
        XMAlbumSubNewView *albumSubNewView = [XMAlbumSubNewView app_viewFromXib];
        self.albumSubNewView = albumSubNewView;
        [albumSubNewView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(albumSubNewViewDidClick)]]; 
    }
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    
    self.albumSubNewView.frame = CGRectMake(0, 0, kScreenWidth, [XMAlbumSubNewView viewHeight]);
    self.tableView.tableFooterView = self.albumSubNewView;
}

#pragma mark - UITableViewDataSource, UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.items.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.items[section].photographUserAngleViews.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    XMAlbumSubCell *cell = [tableView dequeueReusableCellWithIdentifier:Id];
    cell.delegate = self;
    cell.albumType = self.albumType;
//    cell.isUpdataOperate = self.isUpdataOperate;
    cell.albumSubCellOperate = self.isUpdataOperate? XMAlbumSubCellOperateUpload :XMAlbumSubCellOperateNone;
    cell.item = self.items[indexPath.section].photographUserAngleViews[indexPath.row];
    cell.indexPath = indexPath;
    MJWeakSelf
    [cell setDeleteBlock:^{
        
        [XMTitleAlterView showTypeMaterialListWithTitle:@"是否确认删除?" sureBlock:^{
            NSMutableArray *listArr =  weakSelf.items[indexPath.section].photographUserAngleViews;
            XMAlbumSubsubModel * subModel = listArr[indexPath.row];
            [KLProgressHUD showWaitingHUD];
            [AppNetwork album_V2deletePIClistWithID:subModel.id Completion:^(BOOL success,id responseStr, AppError *error) {
                [KLProgressHUD hideHUDWithAnimated:YES];
                if (success) {
                    [listArr removeObject:subModel];
                    [weakSelf.tableView reloadData];
                }else{
                    [KLProgressHUD showErrorHUDWithMessage:[error errorMessage]];
                }
            }];
            
        } cancelBlock:^{
            
        }];

        
    }];
    
    [cell setRemarkBlock:^{
        NSMutableArray *listArr =  weakSelf.items[indexPath.section].photographUserAngleViews;
        XMAlbumSubsubModel * subModel = listArr[indexPath.row];

        [XMShowRemarkView showRemarkViewWithRemarkModel:subModel.partyExtrView2];
        
        
    }];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.isUpdataOperate) {
        return [XMAlbumSubCell topViewH];
    
    }else {
        CGFloat h = 0;
        switch (self.albumType) {
            case XMAlbumSubTypePhotos:
                h = self.items[indexPath.section].photographUserAngleViews[indexPath.row].photoCellHeight;
                break;
                
            case XMAlbumSubTypeCompare:
                h = self.items[indexPath.section].photographUserAngleViews[indexPath.row].compareCellHeight;
                break;
        }
        NSLog(@"llq:%ld--%ld--%f", indexPath.section, indexPath.row, h);
        return h;
    }
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return [XMAlbumSubHeadView viewHeigt];
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    XMAlbumSubHeadView *headView = [XMAlbumSubHeadView app_viewFromXib];
    headView.title = self.items[section].name;
    
    return headView;
}

#pragma mark - XMAlbumSubCellDelegate
- (void)albumSubCell:(XMAlbumSubCell *)cell didCellFold:(BOOL)isFload item:(XMAlbumSubsubModel *)item
{
    item.isFoldAlubm = isFload;
    NSIndexPath * indexPath = cell.indexPath;
    [self.tableView reloadRowAtIndexPath:indexPath withRowAnimation:UITableViewRowAnimationNone];
}

- (void)albumSubCell:(XMAlbumSubCell *)cell didScanImageModel:(AlbumImageModel *)model
{
    //查看图库
//    XMPhotoScanController *vc = [[XMPhotoScanController alloc] init];
//    vc.imageUrl = model.imageUrl;
//    vc.isCompare = (self.albumType == XMAlbumSubTypeCompare);
//    vc.standardUrl = model.originalUrl;
    UIViewController *tmpVc = nil;
    if (self.albumType == XMAlbumSubTypeCompare) {
//        XMPhotoScanController *vc = [[XMPhotoScanController alloc] init];
//        vc.imageUrl = model.imageUrl;
//        vc.isCompare = YES;
//        vc.standardUrl = model.originalUrl;
//        tmpVc = vc;
        XMCompareScanController *vc = [[XMCompareScanController alloc] init];
        vc.standardImageUrl = model.originalUrl;
        vc.outImageUrl = model.imageUrl;
        tmpVc = vc;
    }else{
        XMSinglePicScanController *vc = [[XMSinglePicScanController alloc] init];
        vc.imageUrl = model.imageUrl;
        tmpVc = vc;
    }
    
    UIViewController *current = [UIViewController app_getCurrentVC];
    [current presentViewController:tmpVc animated:YES completion:nil];
}


#pragma mark - KLTableViewPlaceHolderProtocol
- (UIView *)makePlaceHolderView
{
    return [KLNoValueView noValueView];
}

#pragma mark - Action
// 更新图片
- (void)confirmUploadButtonDidClick {
    
    NSMutableArray <NSString *>*idArrayM = [NSMutableArray array];
    for (XMAlbumSubModel *subModel in self.items) {
        for (XMAlbumSubsubModel *subsubModel in subModel.photographUserAngleViews) {
            if (subsubModel.isFoldAlubm) {
                [idArrayM addObject:subsubModel.subSubCateId];
            }
        }
    }
    
    if (idArrayM.count == 0) {
        [KLProgressHUD showPromptHUDWithMessage:@"请选择图库"];
        return;
    }
    
    [self updatePhotoStatusWithIds:[idArrayM componentsJoinedByString:@","]];
}

// 新建项目
- (void)albumSubNewViewDidClick {
     UIViewController *current = [UIViewController app_getCurrentVC];
    
//    XMCameraTimeAndAngleViewController *projectSeleted = [[XMCameraTimeAndAngleViewController alloc] initOldWithPartyId:self.partyId realName:self.realName];
    XMCameraTimeAndAngleViewController * vc = [[XMCameraTimeAndAngleViewController alloc]init];
    vc.partyId = self.partyId;
    [current.navigationController pushViewController:vc animated:YES];
}
#pragma mark - Request
// 图库数据数据请求
- (void)loadAlbumDataRequest
{
    KLProgressHUD *progressHUD = [KLProgressHUD showWaitingHUDWithSuperView:self.view message:kLoadingMsg];
    
    WEAKSELF
    [AppNetwork album_getLibraryWithPartyId:self.partyId completion:^(BOOL success, id response, NSString *errMsg) {
        progressHUD.hidden = YES;
        
        if (success) {

            NSArray * list = [NSArray modelArrayWithClass:[XMAlbumSubModel class] json:response[@"photographUserAngleMapViews"]];
            //添加查看备注和删除
            if (weakSelf.albumType == XMAlbumSubTypePhotos) {
                for (XMAlbumSubModel * subModel in list) {
                    
                    for (XMAlbumSubsubModel * subSubModel in subModel.photographUserAngleViews) {
                        AlbumImageModel * remarkModel = [[AlbumImageModel alloc]init];
                        remarkModel.titleStr = @"查看备注";
                        
                        [subSubModel.photographUserAngleRefViews addObject:remarkModel];
                        
                        AlbumImageModel * deleteModel = [[AlbumImageModel alloc]init];
                        deleteModel.titleStr = @"删除";
                        
                        [subSubModel.photographUserAngleRefViews addObject:deleteModel];
                    }
                    
                }
                
            }
            
 
            weakSelf.items = [NSMutableArray arrayWithArray:list];

            
            [weakSelf.tableView app_reloadData];
            
        }else {
            [KLProgressHUD showErrorHUDWithMessage:errMsg];
        }
    }];
}

- (void)updatePhotoStatusWithIds:(NSString *)ids {
    KLProgressHUD *progressHUD = [KLProgressHUD showWaitingHUDWithSuperView:self.view message:@"上传中.."];
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"ids"] = ids;
    
    [AppNetwork postWithUrl:kUpdatePhotoStatusPath params:param success:^(id response) {
        progressHUD.hidden = YES;
        
        UIViewController *current = [UIViewController app_getCurrentVC];
        
        SuccessToOriginController *success = [[SuccessToOriginController alloc] init];
        [success setNavTitle:@"上传照片" desTitle:@"上传完成" btnTitle:@"确定"];
        success.imageName = @"ic_album_uploadDone";
        [current.navigationController pushViewController:success animated:YES];
        
        [success setBtnClickHandle:^(SuccessToOriginController *btnVC) {
            [btnVC.navigationController popViewControllerAnimated:YES];
        }];
        
        // 把自己移除
        [UIViewController app_removeCurrenStackVCWithCoordinateVC:current removeIndex:0 removeLength:1];
        
    } fail:^(AppError *error) {
        progressHUD.hidden = YES;
        [KLProgressHUD showErrorHUDWithMessage:[error errorMessage]];
    }];
}

#pragma mark - lazy
- (NSMutableArray *)items
{
    if (_items == nil) {
        _items = [NSMutableArray array];
    }
    return _items;
}

- (UITableView *)tableView {
    if (!_tableView) {
        UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        tableView.delegate = self;
        tableView.dataSource = self;
        tableView.sectionIndexColor = HEXPColor(0x2c2e30, 1.0);
//        tableView.backgroundColor = [UIColor groupTableViewBackgroundColor];
        
        tableView.backgroundColor = HEX_RGB(0xf7f7f7);
        
        [tableView registerNib:[UINib nibWithNibName:NSStringFromClass(XMAlbumSubCell.class) bundle:nil] forCellReuseIdentifier:Id];
        tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        
        _tableView = tableView;
    }
    return _tableView;
}

- (UIButton *)confirmUploadButton {
    if (!_confirmUploadButton) {
        _confirmUploadButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_confirmUploadButton setTitle:@"确认上传" forState:UIControlStateNormal];
        [_confirmUploadButton.titleLabel setTextColor:[UIColor whiteColor]];
        [_confirmUploadButton.titleLabel setFont:[UIFont systemFontOfSize:16.f]];
        [_confirmUploadButton setBackgroundImage:[UIImage imageNamed:@"ic_common_bg_main"] forState:UIControlStateNormal];
        
        [_confirmUploadButton addTarget:self action:@selector(confirmUploadButtonDidClick) forControlEvents:UIControlEventTouchUpInside];
    }
    return _confirmUploadButton;
}


-(void)didReceiveMemoryWarning{
    [super didReceiveMemoryWarning];
    [[SDImageCache sharedImageCache]clearMemory];

}

@end
